package com.bbs.service.impl;

import com.bbs.dao.PostDao;
import com.bbs.domain.Page;
import com.bbs.entity.Post;
import com.bbs.entity.User;
import com.bbs.service.PostService;
import com.bbs.utils.MyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

@Component("postService")
public class PostServiceImpl implements PostService {
    @Autowired
    private PostDao postDao;
    private Post post;
    private User user;

    @Override
    public Page<Post> findByPage(int curPage) {
        // 每页记录数
        int limit = 5;
        // 从哪开始 . 假设 curPage=2, 即从第二页开始查，那么 offset=(2-1)*5=5, 即从第五条记录开始查
        int offset = (curPage - 1) * limit;
        // 获得总记录数，总页数
        int allCount = postDao.selectPostCount();
        // 记得在相应的dao增加该方法
        int allPage = 0;
        if (allCount <= limit) {
            allPage = 1;
        } else if (allCount % limit == 0) {
            allPage = allCount / limit;
        } else {
            allPage = allCount / limit + 1;
        }
        // 帖子 数据列表
        List<Post> postList = postDao.findByPage(offset, limit);
        for (Post post : postList) {
            System.err.println(post);
        }
//         封装分页对象信息并返回给控制器
        Page<Post> pageInfo = new Page<>(allPage, curPage);
        pageInfo.setList(postList);
//         给分页对象设置list列表数据
        return pageInfo;
    }

    //发布帖子
    @Override
    public int insertPost(Post post) {
        post.setPublishTime(MyUtil.formatDate(new Date()));
        post.setReplyTime(MyUtil.formatDate(new Date()));
        postDao.insertPost(post);
        postDao.updateUserPostCount(post.getUid());
        return 1;
    }

    @Override
    public Post findById(int pid) {
        postDao.updateById(pid);
        Post byId = postDao.findById(pid);
        return byId;
    }

    @Override
    public int updateById(int pid) {
        return 0;
    }

    @Override
    public int updateUserPostCount(int uid) {

        return 0;
    }

    @Override
    public List<Post> selectUserPost(int uid){
        List<Post> post = postDao.selectUserPost(uid);
        return post;
    }


//    @Override
//    public void findScan() {
//        System.err.println("123");
//        postDao.findScan();
//    }


}
